package com.summer.config;

import com.summer.pojo.Configuration;
import com.summer.pojo.MappedStatement;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.util.List;

public class XMLMapperBuilder {

    private Configuration configuration;

    public XMLMapperBuilder(Configuration configuration) {
        this.configuration = configuration;
    }

    public void parse(InputStream inputStream) throws DocumentException {
        Document document = new SAXReader().read(inputStream);
        Element rootElement = document.getRootElement();
        String namespace = rootElement.attributeValue("namespace");
        //解析select标签
        List<Element> list = rootElement.selectNodes("//select");
        list.stream().forEach(s -> {
            setConfiguration(namespace, s);
        });
        //解析update标签
        List<Element> updateList = rootElement.selectNodes("//update");
        updateList.stream().forEach(s -> {
            setConfiguration(namespace, s);
        });
        //解析delete标签
        List<Element> deleteList = rootElement.selectNodes("//delete");
        deleteList.stream().forEach(s -> {
            setConfiguration(namespace, s);
        });
    }

    private void setConfiguration(String namespace, Element s) {
        String id = s.attributeValue("id");
        String resultType = s.attributeValue("resultType");
        String paramterType = s.attributeValue("paramterType");
        String sqlText = s.getTextTrim();
        MappedStatement mappedStatement = new MappedStatement();
        mappedStatement.setId(id);
        mappedStatement.setResultType(resultType);
        mappedStatement.setParamterType(paramterType);
        mappedStatement.setSql(sqlText);
        String key = namespace + "." + id;
        configuration.getMappedStatementMap().put(key, mappedStatement);
    }
}
